const pool = require("../../config/db");
const Token = require("../../config/token");
module.exports.install = function (express) {
  const login = express.Router();

  login.get("/", function (req, res) {
    pool.query("SELECT * FROM user", function (err, rows, fields) {
      if (err) {
        res.json({
          code: -1,
          message: err,
          data: [],
        });
      } else {
        res.json({
          code: 0,
          message: "查询成功",
          data: rows,
        });
      }
    });
  });
  /**
   * This function comment is parsed by doctrine
   * @route POST /login/user
   * @group foo - Operations about user
   * @param {string} user_name.body.required - user_name
   * @param {string} user_password.body.required - user_password
   * @returns {object} 200 - An array of user info
   * @returns {Error}  default - Unexpected error
   */
  login.post("/user", function (req, res) {
    let user_name = req.body.user_name;
    let user_password = req.body.user_password;
    if (
      typeof user_name === "undefined" ||
      typeof user_password === "undefined"
    ) {
      res.json({
        code: -1,
        message: "账号或密码不能为空",
        data: [],
      });
      return;
    }
    pool.execute(
      "SELECT user_password FROM `user` WHERE `user_name` = ?",
      [user_name],
      function (err, rows) {
        if (rows) {
          if (rows.length === 0) {
            res.json({
              code: -1,
              message: "用户未找到",
              data: [],
            });
          } else {
            let [obj] = rows;
            if (user_password !== obj.user_password) {
              res.json({
                code: -1,
                message: "密码错误",
                data: [],
              });
              return;
            }
            pool.execute(
              "SELECT user_role,user_nickname,user_gender,user_diqu FROM `user` WHERE `user_name` = ?",
              [user_name],
              function (err, rows1) {
                if (err) {
                  res.json({
                    code: -1,
                    message: "密码错误",
                    data: [],
                  });
                } else {
                  res.json({
                    code: 0,
                    message: "登录成功",
                    data: rows1,
                    token: Token.encrypt(
                      {
                        ...rows1[0],
                        user_name,
                        user_password,
                      },
                      3600
                    ),
                  });
                }
              }
            );
          }
        } else {
          res.json({
            code: -1,
            message: err,
            data: [],
          });
        }
      }
    );
  });
  return login;
};
